const jwt = require('jsonwebtoken');

function generateToken(member) {
    if(!member?.id) {
        return null;
    }
    return jwt.sign({id: member.id}, process.env.APP_KEY);
}

function authencation(req, res, next) {
    const token = `${req.headers?.authorization || ''}`.replace(/^Bearer\s/, '');
    // console.log('token', token);
    if(!token) {
        res.status(401);
        res.json({code: 'auth.error', message: '请先登录'});
    }

    // JWT token解析校验
    jwt.verify(token, process.env.APP_KEY, (err, decode) => {
        if(err) {
            res.status(401);
            res.json({code: 'token.expired', message: 'Token过期'});
        }
        else {
            console.log('token decode', decode);
            req.member = decode;
            next();
        }
    });
}

module.exports = {
    generateToken,
    authencation
};